package org.linphone.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.leehuubsd.yiyanzb.R;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.test.AndroidTestCase;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class ContactTest extends AndroidTestCase {
	private SharedPreferences sharedPreferences;
	private Editor edit;

	/*
	 * 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获得系统返回的rawContactId
	 * 这时后面插入data表的数据，只有执行空值插入，才能使插入的联系人在通讯录里面可见
	 */
	public void testInsert(String[] arr, Context context) throws Exception {
		try {
			sharedPreferences = context.getSharedPreferences("bosidengaa",
					Context.MODE_WORLD_READABLE);
			edit = sharedPreferences.edit();
			long id = sharedPreferences.getLong("rawContactId", 0);
			ContentValues values = new ContentValues();
			long rawContactId = 0;
			if (id == 0 || queryNameInfo(context, id + "")) {
				/*
				 * 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获得系统返回的rawContactId
				 */
				if (queryNumbInfo(context, context.getResources().getString(R.string.app_name))) {
					rawContactId = Long.parseLong(PPID);
					edit.putLong("rawContactId", rawContactId);
					edit.commit();
				}else{
					Uri rawContactUri = context.getContentResolver().insert(
							RawContacts.CONTENT_URI, values);
					rawContactId = ContentUris.parseId(rawContactUri);
					edit.putLong("rawContactId", rawContactId);
					edit.commit();
				}
			} else {
				rawContactId = id;
			}
			// 更新姓名
			values.put(StructuredName.GIVEN_NAME, context.getResources()
					.getString(R.string.app_name));
			context.getContentResolver().update(
					ContactsContract.Data.CONTENT_URI,
					values,
					Data.RAW_CONTACT_ID + "=? and " + Data.MIMETYPE + "=?",
					new String[] { rawContactId + "",
							StructuredName.CONTENT_ITEM_TYPE });
			
			// 更新电话
			values.clear();
			values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "");
			context.getContentResolver()
					.update(ContactsContract.Data.CONTENT_URI,
							values,
							Data.RAW_CONTACT_ID + "=? and " + Data.MIMETYPE
									+ "=?",
							new String[] { rawContactId + "",
									Phone.CONTENT_ITEM_TYPE });
			

			// 往data表里写入姓名数据
			values.clear();
			values.put(Data.RAW_CONTACT_ID, rawContactId);
			values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); // 内容类型
			values.put(StructuredName.GIVEN_NAME, context.getResources()
					.getString(R.string.app_name));
			context.getContentResolver().insert(
					android.provider.ContactsContract.Data.CONTENT_URI, values);

			// 往data表里写入电话数据
			for (int i = 0; i < arr.length; i++) {
				values.clear();
				values.put(Data.RAW_CONTACT_ID, rawContactId);
				values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
				values.put(Phone.NUMBER, arr[i]);
				values.put(Phone.TYPE, Phone.TYPE_MOBILE);
				context.getContentResolver().insert(
						android.provider.ContactsContract.Data.CONTENT_URI,
						values);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 查询姓名
	 * */
	private boolean queryNameInfo(Context context, String rawContactId) {
		Cursor cursorOfName = context.getContentResolver().query(
				Data.CONTENT_URI, // 查询data表
				new String[] { Data.DISPLAY_NAME,// 姓名
				}, Data.RAW_CONTACT_ID + " = ? ",
				new String[] { rawContactId }, null);
		String name = null;
		while (cursorOfName.moveToNext()) {
			name = cursorOfName.getString(cursorOfName
					.getColumnIndex(Data.DISPLAY_NAME));
		}
		if (TextUtils.isEmpty(name)) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 根据姓名查询号码
	 * */
	private String PPID;
	private boolean queryNumbInfo(Context context, String rawContactId) {
		Cursor cursorOfName = context.getContentResolver().query(
				Data.CONTENT_URI, // 查询data表RAW_CONTACT_ID
				new String[] { Data.RAW_CONTACT_ID,}, Data.DISPLAY_NAME + " = ? ",new String[] { rawContactId }, null);
		String name = null;
		while (cursorOfName.moveToNext()) {
			PPID = cursorOfName.getString(cursorOfName.getColumnIndex(Data.RAW_CONTACT_ID));
			break;
		}
		if (!TextUtils.isEmpty(PPID)) {
			return true;
		} else {
			return false;
		}
	}

	public void PostDate(final Context context, final String name,
			final String passWord) {
		RequestQueue queue = Volley.newRequestQueue(context);
		StringRequest request = new StringRequest(Method.POST, context
				.getResources().getString(R.string.http)
				+ "/YXBp/dm9zb2Vt/GetBackCallNumbers", new Listener<String>() {

			@Override
			public void onResponse(String arg0) {
				// TODO Auto-generated method stub
				getdate(arg0, context);
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				// TODO Auto-generated method stub
				Log.i("LOG", "!!!!onErrorResponse：" + arg0.toString());
			}
		}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				Map<String, String> map = new HashMap<String, String>();
				map.put("userName", name);
				map.put("password", passWord);
				map.put("proxyId", context.getResources().getString(R.string.oem));
				return map;
			}
		};
		queue.add(request);
	}
	
	public void getdate(String arg0,Context context){
		try {
			JSONTokener jsonTokener = new JSONTokener(arg0);
			JSONObject object = (JSONObject) jsonTokener.nextValue();
			if (object.getInt("retCode") == 0) {
				JSONArray jarray = object.getJSONArray("numbers");
				String[] arr = new String[jarray.length()];
				for (int i = 0; i < jarray.length(); i++) {
					String value = (String) jarray.get(i);
					arr[i] = value.trim();
				}
				try {
					testInsert(arr, context);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
